<?php
declare (strict_types=1);

namespace app\common\model\admin;

use app\common\model\Base as BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 后台API权限模型
 * Class Api
 */
class Api extends BaseModel
{
    // 定义表名
    protected $name = 'admin_api';

    // 定义表主键
    protected $pk = 'api_id';

    protected $append = ["id",'title'];

    public function getIdAttr($value){
        return $this[$this->pk];
    }

    public function getTitleAttr($value){
        return $this["name"];
    }

    public function getCreateTimeAttr($value): string
    {
        return $value?date("Y-m-d H:i:s",$value):'';
    }

    public function getUpdateTimeAttr($value): string
    {
        return $value?date("Y-m-d H:i:s",$value):'';
    }

    /**
     * 获取所有权限
     * @param array $param
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    protected static function getAll(array $param = []): array
    {
        $where = [];

        // 关键词搜索
        !empty($param['search']) && $where[] = ['name', 'like', "%{$param['search']}%"];

        $data =(new static)->where($where)
            ->order(['sort', 'create_time'])
            ->select();
        return !$data->isEmpty() ? $data->toArray() : [];
    }

    /**
     * 权限信息
     * @param array|int $where
     * @return array|null|static
     */
    public static function detail(array|int $where): array|static|null
    {
        return static::get($where);
    }

    /**
     * 获取指定ID集的url
     * @param array $apiIds
     * @return array
     */
    public static function getApiUrls(array $apiIds): array
    {
        return (new static)->where('api_id', 'in', $apiIds)
            ->order(['sort', 'create_time'])
            ->column('url');
    }
}
